// SystemRatingRecommendationModal.jsx
import React, { useEffect, useState } from "react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Card, CardContent } from "@/components/ui/card";
import { CrossingPointAPI } from "@/api/CrossingPoint";

const crossingTypeMap = {
  powerLineOutagePlus500: "跨越电力线路（带电）",
  powerLineOutagePlus110: "  跨越电力线路（不带电）",
  railway: "跨越普通铁路",
  railwayHighSpeed: "跨越高铁",
  firstHighway: "跨越高速公路(含全封闭一级公路)",
  highwayGradePlus2: "跨越公路(二级及以下公路)",
  navigableRivers: "跨越通航河流",
  noNavigableRivers: "跨越不通航河流",
  railwayNormal: "跨越通信线路",
  other: "其它",
};
export default function SystemRatingRecommendationModal({
  isOpen,
  onClose,
  point = {},
  onConfirm,
}) {
  // 评分相关状态

  const [ratingMethods, setRatingMethods] = React.useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 新增：选中的评分方法
  const [selectedMethod, setSelectedMethod] = useState(null);

  // 获取推荐评分方法
  const fetchRatingMethods = async () => {
    if (!point?.id) return;

    try {
      setLoading(true);
      setError(null);
      const response = await CrossingPointAPI.recommend(point.id);

      if (response?.data) {
        // 按得分从高到低排序
        setRatingMethods([...response.data].sort((a, b) => b.score - a.score));
      } else {
        setRatingMethods([]);
      }
    } catch (err) {
      console.error("获取评分方法失败:", err);
      setError("获取推荐方案失败，请稍后重试");
      setRatingMethods([]);
    } finally {
      setLoading(false);
    }
  };

  // 处理确认推荐
  const handleConfirm = () => {
    const ratingData = {
      pointId: point?.id,
      selectedMethod: selectedMethod, // 新增：将选中的方法加入提交数据
    };
    onConfirm(ratingData);
    handleClose()
  };

  const handleClose = () => {
    setSelectedMethod(null); // 重置选中的施工方法
    onClose(); // 调用外部关闭回调
  };
  // 新增：处理评分方法选中
  const handleMethodSelect = (method) => {
    // 如果点击已选中的方法，则取消选中
    if (selectedMethod === method) {
      setSelectedMethod(null);
    } else {
      setSelectedMethod(method);
    }
  };

  // 当弹窗打开且point.id存在时获取数据 
  useEffect(() => {
    if (isOpen && point?.id) {
      fetchRatingMethods();
    }
  }, [isOpen, point?.id]);

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="sm:max-w-[800px]">
        <DialogHeader>
          <DialogTitle>系统评分推荐</DialogTitle>
          <DialogDescription>
            根据跨越点特性设置评分权重，系统将基于这些参数生成最优方案推荐
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-3">
          <div className="space-y-2">
            <Label htmlFor="constructionMethod">跨越点信息</Label>
            <Card className="border rounded-lg shadow-sm hover:shadow-md transition-shadow duration-200">
              <CardContent className="p-3 space-y-2">
                {/* 信息网格布局 */}
                <div className=" flex justify-between">
                  <div>
                    <div className="flex items-center">
                      <Label htmlFor="constructionMethod">名称：</Label>
                      <Label htmlFor="constructionMethod">
                        {point?.name || "未设置"}
                      </Label>
                    </div>
                    <div className="flex items-center mt-3">
                      <Label htmlFor="constructionMethod">跨越对象：</Label>
                      <Label htmlFor="constructionMethod">
                        {point?.crossingObject || "未知"}
                      </Label>
                    </div>
                  </div>

                  <div>
                    <div className="flex items-center">
                      <Label htmlFor="constructionMethod">跨越类型：</Label>
                      <Label htmlFor="constructionMethod">
                        {crossingTypeMap[point?.crossingType] ||
                          point?.crossingType ||
                          "未定义"}
                      </Label>
                    </div>
                    <div className="flex items-center  mt-3">
                      <Label htmlFor="constructionMethod">档距：</Label>
                      <Label htmlFor="constructionMethod">
                        {point?.spanLength
                          ? `${point?.spanLength} 米`
                          : "未测量"}
                      </Label>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
          <div className="space-y-2">
            <Label htmlFor="constructionMethod">
              得分方法（从高到低评分排序）
            </Label>
            <Card className="border rounded-lg shadow-sm hover:shadow-md transition-shadow duration-200">
              <div className="mb-4">
                <div className="p-2 min-h-[100px] max-h-[250px] overflow-y-auto">
                  {loading ? (
                    <div>加载中...</div>
                  ) : error ? (
                    <div className="text-red-500">{error}</div>
                  ) : ratingMethods.length > 0 ? (
                    ratingMethods.map((method, index) => (
                      <div
                        key={index}
                        className={`mb-4 p-3 border rounded-lg shadow-sm hover:shadow-md transition-shadow duration-200 cursor-pointer ${
                          selectedMethod === method
                            ? "border-blue-500 bg-blue-50"
                            : "border-gray-200"
                        }`}
                        onClick={() => handleMethodSelect(method)}
                      >
                        <div className="flex flex-wrap justify-between gap-4">
                          <div className="w-64">
                            <Label
                              htmlFor="constructionMethod"
                              className="w-60 truncate"
                            >
                              方法名称:{" "}
                              {method?.template?.methodName || "未命名"}
                            </Label>
                          </div>
                          <div>
                            <Label
                              htmlFor="constructionMethod"
                              className="w-60 truncate"
                            >
                              得分:{" "}
                              <span className="text-red-600 font-medium">
                                {method?.score ?? "N/A"}
                              </span>
                            </Label>
                          </div>
                          <div>
                            <Label
                              htmlFor="constructionMethod"
                              className="w-60 truncate"
                            >
                              推荐级别:{" "}
                              <span
                                className={`text-gray-800 font-medium ${
                                  method?.recommendationLevel === "不推荐"
                                    ? "text-red-600"
                                    : "text-green-600"
                                }`}
                              >
                                {method?.recommendationLevel || "未设置"}
                              </span>
                            </Label>
                          </div>
                        </div>
                      </div>
                    ))
                  ) : (
                    <Label htmlFor="constructionMethod">暂无推荐方案数据</Label>
                  )}
                </div>
              </div>
            </Card>
          </div>

          <div>
            <div className="flex justify-between items-center">
              <Label htmlFor="selectedMethodInfo">施工方法信息</Label>
            </div>
            <Card className="border rounded-lg p-4 mt-2">
              {selectedMethod ? (
                <div className="space-y-2">
                  <div>
                    <Label
                      htmlFor="constructionMethod"
                      className="w-60 truncate"
                    >
                      方法名称：{" "}
                    </Label>

                    <Label
                      htmlFor="constructionMethod"
                      className="w-60 truncate"
                    >
                      {selectedMethod?.template?.methodName || "未命名"}
                    </Label>
                  </div>
                  <div>
                    <Label
                      htmlFor="constructionMethod"
                      className="inline-block w-24"
                    >
                      方法描述：{" "}
                    </Label>
                    <Label
                      htmlFor="constructionMethod"
                      className="whitespace-pre-wrap break-words"
                    >
                      {selectedMethod?.template?.description || "无描述"}
                    </Label>
                  </div>
                </div>
              ) : (
                <Label
                  htmlFor="selectedMethodInfo"
                  className="text-gray-500 italic"
                >
                  请从上方选择一个推荐的施工方法
                </Label>
              )}
            </Card>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={handleClose}>
            取消
          </Button>
          <Button
            onClick={handleConfirm}
            disabled={!selectedMethod} // 未选中时禁用确认按钮
          >
            生成评分推荐方案
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
